package com.thread.threadfirst.studyThread4;

import java.util.concurrent.*;

/**
 * keepAliveTime：线程池中的线程空闲时间，即线程在多长空闲时间后销毁。当线程池中的线程数大于corePoolSize时，keepAliveTime为多余的（即非核心线程）空闲线程等待新任务的 最长时间，
 * 超过这个时间后多余的线程将被终止（所以此参数并不是说核心线程）。这里把keepAliveTime设置为0L，意味着多余的空闲线程会被立即终止。
 * <p>
 * 如果要设置核心线程的回收，则需要设置：
 * executor.allowCoreThreadTimeOut(true);  //默认为false
 * 但这时keepAliveTime必须要>0才行，否则会抛出异常！！！throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
 * <p>
 * 下面的输出可发现线程2 在执行完task2后 又继续执行了task1，执行完后没有任务可执行了才销毁，之后线程1也执行完了。
 */
public class KeepAliveTimeTest {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1));
        for (int i = 0; i < 3; i++) {
            executor.execute(new MyTest(i));
        }
        while (true) {
            System.out.println("总线程数 " + executor.getPoolSize() + " 当前活跃线程数 " + executor.getActiveCount() + " 任务数 " + executor.getTaskCount());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.println(executor.isTerminated());
        }
    }

    private static class MyTest implements Runnable {

        int i;

        public MyTest(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(i + " Thread = " + Thread.currentThread().getName());
            if (i >= 1) {
                try {
                    Thread.sleep(1000 * 1);
                    System.out.println(i + " sleep 1s end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    Thread.sleep(4000 * 1);
                    System.out.println(i + " sleep 4s end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
